package com.dome.common.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(
    basePackages = {
        "com.dome.dao.mapper"
    },
    sqlSessionFactoryRef = "domeSqlSessionFactory")
public class DomeDBConfig {

  @Bean(name = "domeDataSource")
  @ConfigurationProperties(prefix = "database.dome")
  public DataSource dataSource() {
    return DataSourceBuilder.create().build();
  }

  @Bean(name = "domeTransactionManager")
  public DataSourceTransactionManager transactionManager(@Qualifier("domeDataSource") DataSource dataSource) {
    return new DataSourceTransactionManager(dataSource);
  }

  @Bean(name = "domeSqlSessionFactory")
  public SqlSessionFactory sqlSessionFactory(@Qualifier("domeDataSource") DataSource dataSource)
      throws Exception {
    SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
    factoryBean.setDataSource(dataSource);
    factoryBean.setMapperLocations(
        new PathMatchingResourcePatternResolver()
            .getResources("classpath*:mybatis-mapper/*.xml"));
    return factoryBean.getObject();
  }
}
